/*
 * @Description: axios封装
 * @Author: Cxy
 * @Date: 2024-01-04 10:40:47
 * @LastEditors: Cxy
 * @LastEditTime: 2025-02-23 00:38:51
 * @FilePath: \xy-admin\play\src\api\axios.ts
 */
import axios from 'axios'
import { proxy } from '../../vite.proxy'
import Controller from './controller'

// 创建实例时配置默认值  https://www.axios-http.cn/docs/req_config
const Axios = axios.create({
  timeout: 30000
})

/* 初始化axios控制器  **不用可删掉 */
export const controller = new Controller({ retryCount: 3 }, Axios)

/* 请求拦截器 */
Axios.interceptors.request.use(
  config => {
    // 在发送请求之前做些什么
    config.headers.Authorization =
      'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyIwIjoiNDNhZGMzMGYzZjg5YzVmNjgwNTc5NWVmYzhhNjc5ZWQiLCJpYXQiOjE3MDgyMjIwNTMsImV4cCI6MTcwODMwODQ1M30.aH8TcM1K2E-u7YJAehCN7fxtr5FAMla8fgAZd4Z3rHs'

    // 根据环境及代理配置自动设置基础请求路径
    const proxyMode = proxy[import.meta.env.MODE] ?? proxy['development']
    const urlRegTest = (key: string) => config.url && new RegExp(`^${key}`, 'g').test(config.url)
    if (config.url) {
      const currentProxy = proxyMode.find(c => c.keyAlias && urlRegTest(c.keyAlias))
      if (currentProxy) {
        config.baseURL = urlRegTest(currentProxy.key) ? '' : currentProxy.key
      } else {
        const isDoesExist = proxyMode.some(c => urlRegTest(c.key))
        config.baseURL = isDoesExist ? '' : proxyMode[0].key
      }
    }
    return config
  },
  error => {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

/* 响应拦截器 */
Axios.interceptors.response.use(
  response => {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    return response
  },
  error => {
    // 错误处理
    return Promise.reject(error)
  }
)

export default Axios
